package com.dong.pointviewpager.manager

import android.os.Handler
import android.os.Looper
import androidx.viewpager.widget.ViewPager
import com.dong.pointviewpager.constant.DEFAULT_LOOP_AUTO
import com.dong.pointviewpager.constant.DEFAULT_LOOP_AUTO_TIME
import com.dong.pointviewpager.interfaces.IPagerBean
import com.dong.pointviewpager.widget.LoopViewPager

/**
 * @description:滑动管理控制器
 * @author dong
 * @date 2021/12/16 11:27
 */
class ScrollerManger {

    var autoTime = DEFAULT_LOOP_AUTO_TIME
    var isAuto = DEFAULT_LOOP_AUTO
    var scrollState = ViewPager.SCROLL_STATE_IDLE

    private val mHandler = Handler(Looper.getMainLooper())

    fun <T: IPagerBean> sendScrollMessage(loopViewPager: LoopViewPager<T>, targetIndex: Int? = null, time:Int = autoTime) {
        //取消上一次的计时
        mHandler.removeCallbacksAndMessages(null)
        if (isAuto) {
            mHandler.postDelayed({
                var target = targetIndex
                if(target == null) {
                    target = loopViewPager.currentItem + 1
                }
                if (target < loopViewPager.adapter?.count ?: 0 && scrollState == ViewPager.SCROLL_STATE_IDLE) {
                    loopViewPager.setCurrentItem(target, true)
                }
                sendScrollMessage(loopViewPager)
            }, (time * 1000).toLong())
        }
    }

    fun release() {
        mHandler.removeCallbacksAndMessages(null)
    }

    class Builder {
        fun build(): ScrollerManger {
            return ScrollerManger()
        }
    }
}